﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using ZF.BLL;
using System.Linq.Expressions;
using ZF.BLL;
using System.Linq.Expressions;
using GCELibrary.Current;
using ZF.BLL.Linq;
using System.Web.Script.Services;
using ZF.BLL.Gather;
using System.IO;
namespace ZF.WS
{
    /// <summary>
    /// WebService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    [System.Web.Script.Services.ScriptService]

    public class WebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public bool CheckUserName(string name)
        {
            return SiteInfo.Instance.CheckRegisterAccount(name);

        }
        [WebMethod]
        public bool CheckEmail(string email)
        {
            return SiteInfo.Instance.CheckRegisterEmail(email);
        }
 
        [WebMethod]
        [ScriptMethod]
        public object GetHouseList(string param)
        {


            using (var dc = SiteInfo.CreateDBDataContext())
            {


                var sm = Newtonsoft.Json.JsonConvert.DeserializeObject<SearchModel>(param);

                List<Expression<Func<Model.H_House, bool>>> filterList = new List<Expression<Func<Model.H_House, bool>>>();
                IQueryable<Model.H_House> selector = dc.H_House;
                if (!string.IsNullOrEmpty(sm.area))
                    filterList.Add(p => p.AreaId1 == sm.area.Convert<int>());

                if (!string.IsNullOrEmpty(sm.caid))
                    filterList.Add(p => p.AreaId2 == sm.caid.Convert<int>());


                if (!string.IsNullOrEmpty(sm.dt))
                {
                    var dts = sm.dt.Split(new string[] { "," }, StringSplitOptions.None).Select(p => p.Convert<int>()).ToArray();
                    if (dts.Length == 1)
                        filterList.Add(p => p.DealType == dts[0]);
                    else
                        filterList.Add(p => dts.Contains(p.DealType));
                }
                if (!string.IsNullOrEmpty(sm.pmax))
                    filterList.Add(p => p.Price <= sm.pmax.Convert<int>());
                if (!string.IsNullOrEmpty(sm.pmax))
                    filterList.Add(p => p.Price <= sm.pmax.Convert<int>());
                if (!string.IsNullOrEmpty(sm.pmin))
                    filterList.Add(p => p.Price >= sm.pmin.Convert<int>());
                if (!string.IsNullOrEmpty(sm.tin))
                {
                    if(sm.tin=="4")
                        filterList.Add(p => p.HX_Tin >=4);
                    else
                        filterList.Add(p => p.HX_Tin == sm.tin.Convert<int>());
                }
                if (!string.IsNullOrEmpty(sm.fan))
                {
                    if (sm.fan == "6")
                        filterList.Add(p => p.HX_Fan >= 6);
                    else
                        filterList.Add(p => p.HX_Fan == sm.fan.Convert<int>());
                }
                if (!string.IsNullOrEmpty(sm.ht))
                    filterList.Add(p => p.HouseType == sm.ht);
                foreach (var filter in filterList)
                {
                    selector = selector.Where(filter);
                }

                selector = selector.Where(p => p.Status == 1 && p.IsVerify);
                int pageSize = 20;
                var rowCount = selector.Count();
                int pageCount = rowCount / pageSize;
                if (rowCount % pageSize == 0)
                    pageCount++;
                int pageIndex = 0;
                if (sm.pageIndex >= 0)
                    pageIndex = sm.pageIndex;
                if (sm.pageIndex > pageCount)
                    pageIndex = pageCount;
                var iqPage = selector.OrderByDescending(p => p.AddTime)
                    .Skip(pageIndex * pageSize).Take(pageSize);

                var source = iqPage.ToList().Select(p =>
                {

                    return new HoustModel()
                    {
                        City = SiteInfo.Instance.GetAreaOrDefault(p.AreaId1).Name,
                        Area = DictionaryConfig.HArea.DefaultIfEmpty(a => p.AreaId2.HasValue && a.AreaId == p.AreaId2.Value, new ZF.Model.Dic_Area()).Name.EmptyString(""),
                        Price = p.Price.ToString() + ((p.DealType == 1 || p.DealType == 2) ? "元/月" : "万元/套"),
                        From = p.Form == 1 ? "个人" : "中介",
                        Date = p.AddTime.ToShortDateString(),
                        Title = p.Title,
                        HouseId = p.HouseId,
                        DealType = SiteInfo.Instance.GetHouseDelt(p.DealType),
                        HouseModel = string.Format("{0}房{1}厅", p.HX_Fan, p.HX_Tin),
                        HouseType = p.HouseType,

                    };
                }).ToList();
                var info = new HouseRespInfo()
                {
                    Data = source,
                    PageCount = pageCount,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    RowCount = rowCount,
                };
                var str = Newtonsoft.Json.JsonConvert.SerializeObject(info);
                return str;


            }
        }
        /// <summary>
        /// 移动贡品
        /// </summary>
        /// <param name="bid"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        [WebMethod]
        [ScriptMethod]
        public void MoveGP(int bid, int x, int y)
        {

            using (var dc = SiteInfo.CreateDBDataContext())
            {
                var bowing = dc.G_Bowing.FirstOrDefault(p => p.BowingId == bid);
                if (bowing != null)
                {
                    bowing.X = x;
                    bowing.Y = y;
                }
                dc.SubmitChanges();
            }
 
        }
        [WebMethod]
        [ScriptMethod]
        public bool GatherHouse(string str,string key,bool isTelImg,int dt )
        {

            


           var m= str.JsonConvert<HouseGatherModel>();
           using (var dc = SiteInfo.CreateDBDataContext())
           {
               var oCacheHouse = HttpCache.GetCache("Service_GatherHouse");
               List<string> cacheHouse = new List<string>();

               if (oCacheHouse == null)
               {
                   cacheHouse = dc.H_House.Where(p => p.AddTime > DateTime.Now.AddDays(-2) && p.GatherKey != null).Select(p => p.GatherKey)
                      .Distinct().ToList();
                   HttpCache.SetCache("Service_GatherHouse", cacheHouse);
               }
               else
               {
                   cacheHouse=(List<string>)oCacheHouse;
               }
               if (cacheHouse.Contains(key))
                   return false;


               try
               {
                   var cfgs = m.config.EmptyString("").Split(' ');
                   var h = new Model.H_House()
                   {
                       Address = m.address,
                       Age = m.房零,
                       BaseFacility = DictionaryConfig.HBaseFacility.Where(p => cfgs.Contains(p.Text)).Select(p => p.Key).ConstituteString(),
                       Contact = m.contract,
                       DealType = dt,
                       CutNum = m.clo,
                       UserArea = m.面积,
                       Price = (int)m.price.Convert<decimal>(),
                       HX_Fan = m.fan.Convert<int>(0),
                       HX_Chu = 0,
                       HX_Wei = m.wei.Convert<int>(0),
                       Phone = m.telimg,
                       Title = m.title,

                       HX_Tin = m.tin.Convert<int>(0),
                       TopNum = m.tlo,
                       Payment = m.Payment,
                       ConstructArea =null,
                       Direction = m.朝向,
                       Description = m.info,
                       Decoration = m.装修,
                       HouseType = m.HouseType,
                       HX_Yan = 0,
                       Engage = "联系看房",
                       IsMemberPub = false,
                       MemberId = 0,
                       Period = "30",
                       Periphery = DictionaryConfig.HPeriphery.Where(p => cfgs.Contains(p.Text)).Select(p => p.Key).ConstituteString(),
                       Photo = "",
                       IsBoutique = false,
                       IsVerify = true,
                       PubPwd = "",
                       PubEmail = "--",
                       QQ = "--",
                       Status = 1,
                       Traffic = "",

                       WithFacility = DictionaryConfig.HWithFacility.Where(p => cfgs.Contains(p.Text)).Select(p => p.Key).ConstituteString(),
                       H_Rent = new ZF.Model.H_Rent()
                       {
                           LeastNum = 1,
                       },
                       H_Sell = new ZF.Model.H_Sell()
                       {
                       },

                       Form = isTelImg ? 1 : 2,
                       AddTime = m.Time,
                       AreaId1 = m.area1Id,
                       AreaId2 = m.area2Id == 0 ? default(Nullable<int>) : m.area2Id,

                       GatherKey = key,
                       IsImgTel = isTelImg,
                   };
                   dc.H_House.InsertOnSubmit(h);
                   dc.SubmitChanges();
                   if (isTelImg)
                   {
                       File.WriteAllBytes(Server.MapPath("~/Photo/House/" + m.telimg), m.imgBuff);

                   }
                   cacheHouse.Add(key);
               }
               catch (Exception ex)
               { 
                   
                   return false; 
               }
               return true;
           }
        }
        static List<Model.Dic_InforType> _InfoTypeList = null;
        static List<Model.Dic_InforType> InfoTypeList
        {
            get
            {
                if(_InfoTypeList==null)
                {
                    using (var dc = SiteInfo.CreateDBDataContext())
                    {
                        _InfoTypeList=dc.Dic_InforType.ToList();
                    }
                }
                return _InfoTypeList;

            }
        }
        [WebMethod]
        [ScriptMethod]
        public bool GatherInfo(string str)
        {
             
            var info = str.JsonConvert<InfoModel>();
     
            using (var dc = SiteInfo.CreateDBDataContext())
            {
                var oCacheInfo = HttpCache.GetCache("Service_GatherInfo");
                List<string> cacheHouse = new List<string>();

                if (oCacheInfo == null)
                {
                    cacheHouse = dc.I_Info.Where(p => p.AddTime > DateTime.Now.AddDays(-2) && p.GatherKey != null).Select(p => p.GatherKey)
                       .Distinct().ToList();
                    HttpCache.SetCache("Service_GatherInfo", cacheHouse);
                }
                else
                {
                    cacheHouse = (List<string>)oCacheInfo; 
                }
                if (cacheHouse.Contains(info.key))
                    return false;


                try
                {
                    var p=info;
                    Random ran = new Random();
                    var m=ran.Next(60 * 60 * 10);
                    var date = DateTime.Now.AddDays(-1).AddSeconds(m);
                    var typeName = InfoTypeList.FirstOrDefault(p1 => p1.Name == info.type);
                    if (typeName == null) return false;
                    var mInfo = new Model.I_Info()
                    {
                        AreaId1 = p.area,
                        Contact = p.name,
                        GatherKey = p.key,
                        Phone = p.phone,
                        Price = (int)p.price,
                        Status = 1,
                        Title = p.title,
                        Content = p.body,
                        InfoTypeId = typeName.InfoTypeId,
                        IsTop = false,
                        IsCompany = false,
                        IsVerify = true,
                        Address = "",
                        MemberId = 0,
                        AddTime = date,
                         Email=p.email,
                          QQ=p.qq,
                    };
                    dc.I_Info.InsertOnSubmit(mInfo);
                    dc.SubmitChanges();
                    cacheHouse.Add(info.key);
                }
                catch (Exception ex)
                {

                    return false;
                }
                return true;
            }
        }
    }
    public class InfoModel
    {
        public decimal price;
        public string title;
        public string name;
        public string phone;
        public string body;
        public string date;
        public int area;
        public string key;
        public string type;
        public string email;
        public string qq;
    }
      class SearchModel
    {
          public string caid { get; set; }//二级地区
        public string area { get; set; }//一级地区
        public string dt { get; set; }
        public string pmax { get; set; }
        public string pmin { get; set; }
        public string tin { get; set; }
        public string fan { get; set; }
        public string ht { get; set; }
        public int pageIndex { get; set; }
    }
      class HouseRespInfo
    {
        public List<HoustModel> Data { get; set; }
        public int PageSize { get; set; }
        public int PageCount { get; set; }
        public int RowCount { get; set; }
        public int PageIndex { get; set; }
    }
      class HoustModel
    {
        public string HouseType { get; set; }
        public int HouseId { get; set; }
        public string City { get; set; }
        public string Area { get; set; }
        public string Price { get; set; }
        public string From { get; set; }
        public string Date { get; set; }
        public string DealType { get; set; }
        public string HouseModel { get; set; }
        public string Title { get; set; }
        
    }
}
